<script setup>

import {ref, onMounted, watch} from 'vue';
import {ElButton, ElTable, ElTableColumn, ElPagination, ElMessageBox, ElMessage} from 'element-plus';
import {
  ActivateAdPlan, AddAdUnit,
  CreateAdPlan,
  DeactivateAdPlan,
  GetAdPlans,
  GetAdUnitsForPlan,
  RemovePlan,
  UpdateAdPlan
} from "@/api/index.js";
import useUserInfoStore from "@/store/user.js";

const userStore = useUserInfoStore();

const adPlans = ref([]); // 广告计划列表
const totalItems = ref(0); // 总条目数
const currentPage = ref(1); // 当前页
const pageSize = ref(10); // 每页条目数
const sortField = ref(''); // 默认按照名称排序

const isCreateDialogVisible = ref(false); // 控制创建广告计划对话框的显示
const newAdPlan = ref({//创建新广告计划
  name: '',
  budget: '',
});

// 编辑框相关数据
const isDialogVisible = ref(false); // 控制对话框的显示与隐藏
const currentAdPlan = ref({}); // 当前正在编辑的广告计划

const isAdUnitDialogVisible = ref(false);  // 控制广告单元详情对话框的显示

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


const openCreateDialog = () => {
  isCreateDialogVisible.value = true;
};

// 获取广告计划列表
const getAdPlans = async () => {
  try {
    const response = await GetAdPlans({
      page: currentPage.value,
      page_size: pageSize.value,
      order_by: sortField.value, // 传递排序字段
      search: searchText.value, // 传递搜索关键词
    });
    adPlans.value = response.results;
    totalItems.value = response.count; // 更新总条目数
  } catch (error) {
    console.error('Error fetching ad plans:', error);
  }
};

// 处理页码变动
const handlePageChange = (page) => {
  currentPage.value = page;
  getAdPlans();
};
// 处理排序字段变化
const handleSortChange = () => {
  getAdPlans();  // 排序字段变化时重新获取广告计划数据
};


// 删除广告计划
const deleteAdPlan = (id) => {
  ElMessageBox.confirm(
      '确定删除此广告计划吗?',
      '删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  ).then(async () => {
    try {
      await RemovePlan(id);
      adPlans.value = adPlans.value.filter(item => item.id !== id);
      totalItems.value--;
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('网络错误，请稍后尝试删除！')
    }
  })
};
const activateAdPlan = (id) => {
  ElMessageBox.confirm(
      '确定激活此广告计划吗?',
      '激活',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  ).then(
      async () => {
        try {
          await ActivateAdPlan(id);
          // 更新当前行的状态
          const plan = adPlans.value.find(item => item.id === id);
          if (plan) {
            plan.status = 'active';  // 设置状态为已激活
          }
          ElMessage.success('广告计划已激活');
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试！')
        }
      }
  )
}

const createAdPlan = async () => {
  if (!newAdPlan.value.name || !newAdPlan.value.budget) {
    ElMessage.error('请填写所有必填字段');
    return;
  }
  try {
    // 调用 API 创建广告计划
    await CreateAdPlan({
      name: newAdPlan.value.name,
      budget: newAdPlan.value.budget,
    });

    // 如果成功，刷新广告计划列表并提示成功信息
    ElMessage.success('广告计划创建成功');
    await getAdPlans();  // 刷新广告计划列表
    // 关闭创建对话框
    isCreateDialogVisible.value = false;
  } catch (error) {
    // 出现错误时，显示错误提示
    ElMessage.error('创建广告计划失败，请稍后再试');
  }
}

const deactivateAdPlan = (id) => {
  ElMessageBox.confirm(
      '确定停用此广告计划吗?',
      '停用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  ).then(
      async () => {
        try {
          await DeactivateAdPlan(id);
          // 更新当前行的状态
          const plan = adPlans.value.find(item => item.id === id);
          if (plan) {
            plan.status = 'inactive';  // 设置状态为未激活
          }
          ElMessage.warning('广告计划已停用');
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试！')
        }
      }
  )
}

// 编辑广告计划
const editAdPlan = (id) => {
  // 查找要编辑的广告计划
  const plan = adPlans.value.find(item => item.id === id);
  if (plan) {
    // 将广告计划的数据存入 currentAdPlan，确保不直接修改原始数据
    currentAdPlan.value = {...plan};
    // 打开编辑对话框
    isDialogVisible.value = true;
  } else {
    ElMessage.error('未找到对应的广告计划');
  }
};
// 更新广告计划
const updateAdPlan = async () => {
  if (!currentAdPlan.value.name || !currentAdPlan.value.budget) {
    ElMessage.error('请填写所有必填字段');
    return;
  }

  try {
    // 调用 API 更新广告计划
    await UpdateAdPlan(currentAdPlan.value.id, {
      name: currentAdPlan.value.name,
      budget: currentAdPlan.value.budget,
    });

    // 如果成功，刷新广告计划列表并提示成功信息
    ElMessage.success('广告计划更新成功');
    await getAdPlans();  // 刷新广告计划列表
    // 关闭编辑对话框
    isDialogVisible.value = false;
  } catch (error) {
    // 出现错误时，显示错误提示
    ElMessage.error('更新广告计划失败，请稍后再试');
  }
};
const getPositionTypeLabel = (type) => {
  switch (type) {
    case 0:
      return '开屏';
    case 1:
      return '贴片';
    case 2:
      return '中贴';
    case 3:
      return '暂停贴';
    case 4:
      return '后贴';
    default:
      return '未知';
  }
};
const adUnits = ref([]);  // 用于存储广告单元数据

// 查看广告单元详情
const viewAdUnits = async (adPlanId) => {
  try {
    const response = await GetAdUnitsForPlan(adPlanId);  // 使用API获取广告单元
    adUnits.value = response;
    isAdUnitDialogVisible.value = true;  // 打开对话框
    currentAdPlan.value.plan_id = adPlanId
  } catch (error) {
    ElMessage.error('无法加载广告单元，请稍后重试');
  }
};
const isAdUnitFormVisible = ref(false);
const newAdUnit = ref({
  unit_name: '',
  position_type: 0,
  budget_fee: 0,
});
const toggleAdUnitForm = () => {
  isAdUnitFormVisible.value = true;
  // 清空表单数据
  newAdUnit.value = {
    unit_name: '',
    position_type: 0,
    budget_fee: 0,
  };
};

// 创建广告单元的函数
const createAdUnit = async () => {
  if (!newAdUnit.value.unit_name || !newAdUnit.value.budget_fee) {
    ElMessage.error('请填写所有必填字段');
    return;
  }
  try {
    await AddAdUnit({
      plan_id: currentAdPlan.value.plan_id,  // 绑定的广告计划ID
      ...newAdUnit.value,
    });

    // 成功后刷新广告单元列表并关闭对话框
    await viewAdUnits(currentAdPlan.value.plan_id);
    ElMessage.success('广告单元添加成功');
    isAdUnitFormVisible.value = false;
  } catch (error) {
    // 捕获错误并显示后端返回的错误信息
    if (error.response && error.response.data) {
      const errorMessage = error.response.data.message || error.response.data.budget_fee[0]
          || '添加广告单元失败，请稍后再试';
      ElMessage.error(errorMessage);
    } else {
      // 如果没有响应数据，显示通用错误信息
      ElMessage.error('网络错误，请稍后再试');
    }
  }
};
// 页面加载时获取广告计划
onMounted(getAdPlans);
const searchText = ref(''); // 搜索关键词
// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置到第一页
  getAdPlans();
};
// 监听搜索关键词的变化，添加防抖
let searchTimeout = null;
watch(searchText, () => {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    handleSearch();
  }, 300); // 300ms 防抖
});
const formatCurrency = (row, column, cellValue, index) => {
  const value = Number(cellValue).toLocaleString('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  });
  return value;
};


</script>

<template>
  <div class="ad-plans-container">
    <!-- 创建广告计划按钮 -->
    <div class="action-bar">
      <el-button @click="openCreateDialog" type="primary">创建广告计划</el-button>
    </div>
    <div class="header">
      <h1>广告计划列表</h1>
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
            v-model="searchText"
            placeholder="请输入广告计划名称搜索"
            clearable
            @clear="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" icon="el-icon-search"></el-button>
          </template>
        </el-input>
      </div>
      <!-- 排序选择 -->
      <div class="sort-container">
        <el-select v-model="sortField" placeholder="排序" @change="handleSortChange">
          <el-option label="广告计划名称" value="name"></el-option>
          <el-option label="预算" value="budget"></el-option>
          <el-option label="状态" value="status"></el-option>
          <el-option label="创建时间" value="create_time"></el-option>
        </el-select>
      </div>
    </div>
    <!-- 表格展示广告计划列表 -->
    <el-table :data="adPlans" style="width: 100%" stripe>
      <el-table-column label="广告计划名称" prop="name"></el-table-column>
      <el-table-column label="预算" prop="budget" align="center" :formatter="formatCurrency"></el-table-column>
      <el-table-column label="状态" prop="status" align="center">
        <template #default="{ row }">
          <span>{{ row.status === 'active' ? '已激活' : '未激活' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" align="center">
        <template #default="{ row }">
          <span>{{ formatDate(row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="update_time">
        <template #default="{ row }">
          <span>{{ formatDate(row.update_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #default="{ row }">
          <el-button-group>
            <el-button @click="editAdPlan(row.id)" type="primary" size="small">编辑</el-button>
            <el-button @click="deleteAdPlan(row.id)" type="danger" size="small">删除</el-button>
            <el-button @click="viewAdUnits(row.id)" type="info" size="small">查看广告单元</el-button>
            <!-- 激活(停用)按钮仅管理员可见 -->
            <el-button
                v-if="userStore.userInfo.status === 1 && row.status !== 'active'"
                @click="activateAdPlan(row.id)"
                type="success"
                size="small"
            >
              激活
            </el-button>
            <el-button
                v-if="userStore.userInfo.status === 1 && row.status === 'active'"
                @click="deactivateAdPlan(row.id)"
                type="warning"
                size="small"
            >
              停用
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
        v-if="totalItems > 0"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        @current-change="handlePageChange"
        layout="total, prev, pager, next, jumper"
        class="custom-pagination"
    ></el-pagination>
  </div>

  <!-- 创建广告计划dialog -->
  <el-dialog v-model="isCreateDialogVisible" title="创建广告计划">
    <el-form :model="newAdPlan" ref="createAdPlanForm" label-width="100px">
      <el-form-item label="广告计划名称" :rules="[{ required: true, message: '请输入广告计划名称', trigger: 'blur' }]">
        <el-input v-model="newAdPlan.name"></el-input>
      </el-form-item>
      <el-form-item label="预算" :rules="[{ required: true, message: '请输入预算', trigger: 'blur' }]">
        <el-input v-model="newAdPlan.budget" type="number"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
        <el-button @click="isCreateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createAdPlan">创建</el-button>
      </span>
  </el-dialog>
  <!-- 编辑广告计划dialog -->
  <el-dialog v-model="isDialogVisible" title="编辑广告计划">
    <el-form :model="currentAdPlan" ref="adPlanForm" label-width="100px">
      <el-form-item label="广告计划名称">
        <el-input v-model="currentAdPlan.name"></el-input>
      </el-form-item>
      <el-form-item label="预算">
        <el-input v-model="currentAdPlan.budget"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-input :value="currentAdPlan.status === 'active' ? '已激活' : '未激活'" disabled></el-input>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-input :value="formatDate(currentAdPlan.create_time)" disabled></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAdPlan">更新</el-button>
      </span>
  </el-dialog>

  <!-- 查看广告单元 Dialog -->
  <el-dialog v-model="isAdUnitDialogVisible" title="广告单元详情">
    <div class="add-ad-unit-btn">
      <el-button @click="toggleAdUnitForm" type="primary">添加广告单元</el-button>
    </div>
    <el-table :data="adUnits" style="width: 100%" stripe>
      <el-table-column label="广告单元名称" prop="unit_name"></el-table-column>
      <el-table-column label="状态" prop="unit_status">
        <template #default="{ row }">
          <span>{{ row.unit_status === 1 ? '启用' : '未启用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告位类型" prop="position_type">
        <template #default="{ row }">
          <span>{{ getPositionTypeLabel(row.position_type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预算" prop="budget_fee"></el-table-column>
      <el-table-column label="创建时间" prop="create_time">
        <template #default="{ row }">
          <span>{{ formatDate(row.create_time) }}</span>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加广告单元的表单 -->
    <el-dialog v-model="isAdUnitFormVisible" title="添加广告单元" width="300px">
      <el-form :model="newAdUnit" ref="createAdUnitForm" label-width="80px">
        <el-form-item label="广告单元名称">
          <el-input v-model="newAdUnit.unit_name"></el-input>
        </el-form-item>
        <el-form-item label="广告位类型">
          <el-select v-model="newAdUnit.position_type" placeholder="请选择类型">
            <el-option label="开屏" :value="0"></el-option>
            <el-option label="贴片" :value="1"></el-option>
            <el-option label="中贴" :value="2"></el-option>
            <el-option label="暂停贴" :value="3"></el-option>
            <el-option label="后贴" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预算">
          <el-input v-model="newAdUnit.budget_fee" type="number"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createAdUnit">添加</el-button>
        <el-button @click="isAdUnitFormVisible = false">关闭</el-button>
    </span>
    </el-dialog>
  </el-dialog>

</template>

<style scoped lang="less">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .sort-container {
    width: 200px;
  }

  .search-container {
    width: 300px;
    margin-right: 20px;
  }
}

.el-button-group {
  display: flex;
  gap: 10px; /* 按钮之间的间距 */
  flex-wrap: wrap; /* 如果按钮过多，自动换行 */
}

</style>